﻿/**
 * TraceListeners.cs
 * 
 * AUTHOR:
 * Zlatko Michailov (http://blogs.msdn.com/esql)
 * 
 * PURPOSE:
 * Convert Debug.Assert() into a text message, and eventually throw an exception.
 * This is for internal purposes only - to test debug builds. Without such a conversion
 * the web shell pops dialogs on the server console, and the user keeps waiting.
 * 
 * COPYRIGHT:
 * (c) Microsoft Corp., 2006-2007
 */



using System;
using System.Text;
using System.Diagnostics;



namespace Microsoft.Samples.Data.eSqlBlast
{
    public class StringTraceListener : DefaultTraceListener
    {
        // Data memebers
        private StringBuilder _Builder = new StringBuilder();
        private bool _IncludeCallstack;


        // Constructors
        public StringTraceListener()
            : base()
        {
            _IncludeCallstack = true;
        }


        public StringTraceListener(bool includeCallstack)
            : base()
        {
            _IncludeCallstack = includeCallstack;
        }


        // Overridables
        public override void Fail(string message)
        {
            HandleFail(message, null);
        }


        public override void Fail(string message, string detailMessage)
        {
            HandleFail(message, detailMessage);
        }


        public override string ToString()
        {
            return _Builder.ToString();
        }
        

        // Protected virtual methods
        protected virtual void AfterFail()
        {
        }

        
        // Private helpers
        private void HandleFail(string message, string detailMessage)
        {
            _Builder.AppendFormat("--- ASSERT FAILED ---");

            if (!string.IsNullOrEmpty(message))
            {
                _Builder.AppendFormat("\n{0}", message);
            }

            if (!string.IsNullOrEmpty(detailMessage))
            {
                _Builder.AppendFormat("\n{0}", detailMessage);
            }

            if (_IncludeCallstack)
            {
                _Builder.AppendFormat("\n\n{0}", new TraceEventCache().Callstack.ToString());
            }

            _Builder.Append("\n\n\n");

            // Invoke the virtual method to allow derived
            // classes to handle the Fail event.
            AfterFail();
        }
    }



    public class ExceptionTraceListener : StringTraceListener
    {
        // Constructors
        public ExceptionTraceListener()
            : base(false)
        {
        }


        // Overridables
        protected override void AfterFail()
        {
            throw new ApplicationException(base.ToString());
        }
    }

}
